﻿/***********************************************************************
 * <copyright file="AccountingRepositoryBase.cs" company="BSD JSC">
 * -->    Copyright (C) statement. All right reserved
 * </copyright>
 * 
 * Created:   Hoang Bich Son 
 * Email:    sonhb@newman.vn
 * Website:
 * Create Date: Friday, May 16, 2014
 * Usage: 
 * 
 * RevisionHistory: 
 * Date         Author               Description 
 * 
 * ************************************************************************/

using System;
using System.ServiceModel;
using System.Web;
using DxMvcApplication.AccountingServiceReference;

namespace DxMvcApplication.Repositories.Core.Dictionary
{
    /// <summary>
    /// AccountingRepositoryBase class
    /// </summary>
    public abstract class AccountingRepositoryBase
    {
        /// <summary>
        /// Gets the client.
        /// </summary>
        /// <value>
        /// The client.
        /// </value>
        protected ActionAccountingServiceClient AccountingServiceClient
        {
            get
            {
                // Check if not initialized yet
                if (HttpContext.Current.Session["AccoutingServiceClient"] == null)
                    HttpContext.Current.Session["AccoutingServiceClient"] = new ActionAccountingServiceClient();

                // If current client is 'faulted' (due to some error), create a new instance.
                var client = HttpContext.Current.Session["AccoutingServiceClient"] as ActionAccountingServiceClient;
                if (client != null && client.State == CommunicationState.Faulted)
                {
                    try { client.Abort(); }
                    catch { /* no action */ }

                    client = new ActionAccountingServiceClient();
                    HttpContext.Current.Session["AccoutingServiceClient"] = client;
                }
                return client;
            }
        }

        /// <summary>
        /// Correlates requestid with returned response correlationId.
        /// These must always match. If not, request and responses are not related.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="response">The response.</param>
        /// <exception cref="System.ApplicationException">RequestId and CorrelationId do not match.</exception>
        protected void Correlate(RequestBase request, ResponseBase response)
        {
            if (request.RequestId != response.CorrelationId)
                throw new ApplicationException("RequestId and CorrelationId do not match.");
        }

    }
}